#!usr/bin/env python3
# -*- encoding: utf-8 -*-

import subprocess
import os
import re

emulator_ip = "127.0.0.1"


def open_file(f):
    open_command = 'xdg-open'  # linux?
    if os.name == 'nt':
        open_command = 'start'
    elif os.name == 'mac' or os.name == 'os2':
        open_command = 'open'
    sh("%s %s" % (open_command, f))


def sh(command, print_msg=True):
    p = subprocess.Popen(
        command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    result = p.stdout.read().decode('utf-8')
    if print_msg:
        print(result)
    return result


def adb_connect(ip, port):
    sh("adb connect %s:%s" % (ip, port))


def adb_disconnect(ip, port):
    sh("adb disconnect %s:%s" % (ip, port))


def check_adb_connectable_by_port(port, auto_disconnect=True):
    result = check_adb_connectable_by_ports(
        [port], auto_disconnect=auto_disconnect)
    return len(result) > 0 and result[0] == port


def check_adb_connectable_by_ports(ports, auto_disconnect=True):
    devices = []
    for port in ports:
        device = "%s:%s" % (emulator_ip, port)
        os.system("adb connect %s" % (device))
        devices.append(device)
    result = check_adb_connected(devices)
    if auto_disconnect:
        for device in devices:
            os.system("adb disconnect %s" % (device))
    ports = [int(x.split(':')[1]) for x in result]
    return ports


def check_adb_connected(devices):
    # check if device is active
    active_result = sh("adb devices", print_msg=False)
    connected_devices = []
    for device in devices:
        if re.search(r"%s\s+device" % (device), active_result):
            connected_devices.append(device)
    return connected_devices


def check_has_connected_devices():
    active_result = sh("adb devices", print_msg=False)
    if len(active_result.strip().split('\n')) > 1:
        result = sh('adb shell getprop ro.build.version.sdk', print_msg=False)
        if 'not devices' not in result:
            return True
    return False


def props(obj):
    pr = {}
    for name in dir(obj):
        value = getattr(obj, name)
        if not name.startswith('__') and not callable(value):
            pr[name] = value
    return pr
